import {createRouter, createWebHistory} from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from "@/views/LoginView.vue";
import Layout from "@/components/Layout.vue";
import {ElNotification} from "element-plus";
import UserView from "@/views/UserView.vue";
import PhotoView from "@/views/PhotoView.vue";
import SettingView from "@/views/SettingView.vue";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'login',
            component: LoginView
        },
        {
            path: '/home',
            name: 'layout',
            component: Layout,
            beforeEnter: (to, from, next) => {
                // 获取 token
                const tokenString = localStorage.getItem('token');

                // 检测 token 是否存在
                if (tokenString) {
                    try {
                        const token = JSON.parse(tokenString);
                        ElNotification({
                            title: '登录成功',
                            message: '欢迎回来，' + token.user.nickname,
                            type: 'success',
                        });
                        next(); // 允许继续路由导航
                    } catch (error) {
                        ElNotification({
                            title: '登录失败',
                            message: 'Token 解析失败，请重新登录',
                            type: 'error',
                        });
                        next('/'); // 如果解析失败，可以重定向到登录页面
                    }
                } else {
                    next('/'); // 如果没有 token，重定向到登录页面
                }
            },
            children: [
                {
                    path: '/home',
                    name: 'home',
                    component: HomeView
                },
                {
                    path: '/user',
                    name: '/user',
                    component: UserView
                },
                {
                    path: '/photo',
                    name: 'PhotoView',
                    component: PhotoView
                },
                {
                    path: '/setting',
                    name:'setting',
                    component: SettingView
                }
            ]
        }
    ]
})

export default router
